package com.newfiber.common.core.config;

import com.newfiber.common.core.web.support.QueryDeletedInterceptor;
import java.util.List;
import javax.annotation.PostConstruct;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

/**
 * @author : X.K
 * @since : 2023/5/6 上午9:21
 */
@Configuration
public class InterceptorConfig {

    @Autowired(required = false)
    private List<SqlSessionFactory> sqlSessionFactoryList;

    @PostConstruct
    public void addInterceptor() {
	    if(CollectionUtils.isEmpty(sqlSessionFactoryList)){
		    return;
	    }

	    QueryDeletedInterceptor queryDeletedInterceptor = new QueryDeletedInterceptor();
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
            org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();
            if(!containsInterceptor(configuration, queryDeletedInterceptor)){
                sqlSessionFactory.getConfiguration().addInterceptor(queryDeletedInterceptor);
            }
        }
    }

    private boolean containsInterceptor(org.apache.ibatis.session.Configuration configuration, Interceptor interceptor) {
        try {
            return configuration.getInterceptors().contains(interceptor);
        } catch (Exception ignore) {
            return false;
        }
    }

}
